# -*- coding: utf-8 -*-
"""Excel AquaScope.ipynb

Automatically generated by Colab.

Original file is located at
    https://colab.research.google.com/drive/1f3nLD0E3cxEJyJl7j877HihfJT4L9E7d
"""

import os
import pathlib
import pandas as pd
import PIL.Image
import textwrap
import time
import google.generativeai as genai

from IPython.display import display
from IPython.display import Markdown

data_list = []
site_list = []
# Replace 'your_file.xlsx' with the actual filename
filepath = 'data_coll.xlsx'

# Read the Excel file
df = pd.read_excel(filepath)

# Define a function to process each site
def process_site(site_name, measurements):
    print(f"\n**Site: {site_name}**")
    site_list.append(site_name)
    for i, measurement in enumerate(measurements):
        print(f"Measurement {i+1}: {measurement}")
        data_list.append(measurement)

# Apply the function to each site
for site_name, measurements in df.items():
    process_site(site_name, measurements)
del data_list[:12]
print(data_list)
del site_list[0]
print(site_list)

genai.configure(api_key='AIzaSyDZamT2QUy1I7QPapdV75BgnbzkDmBcSHY')
# genai.configure(api_key='AIzaSyAaOvo4JvUR-PHpn1w_tnsRomzBvYCWsv8')

def prompt_all(context, measurements, image):
    combined_input = [
          str(context) + " " + str(measurements)+ " Use the data collected, location, time provided, the image provided to indentify if this area has a good aquatic health. If not, identify specific aquatic problems (ex. alagal blooms, oil, watse, etc.) Use factors/objects from both of the two images in the aquatic problem identification. If identified in the images, how can oragnisms impact water quality?",
          image
      ]
    return combined_input

def prompt_image(image):
    combined_input = [
          " Use the image provided to indentify if this area has a good aquatic health. If not, identify specific aquatic problems (ex. alagal blooms, oil, watse, etc.) Use factors/objects from the image in the aquatic problem identification. If there are organisms identified in the image discuss if they can impact water quality.",
          image,
      ]
    return combined_input

def prompt_image_context(context, image):
    combined_input = [
          str(context) + " Use the information about my location and time with the image provided to indentify if this area has a good aquatic health, and if present, identify specific possible aquatic problems (ex. alagal blooms, oil, waste, etc.) Use factors/objects from both of the two images in the aquatic problem identification. If identified in the images, how can oragnisms impact water quality?",
          image,
      ]
    return combined_input

def prompt_sensor_context(context, measurements):
    combined_input = [
          str(context) + " " + str(measurements)+ " Use the data collected location, and time provided to assess if this site's aqautic health, and if present, identify specific possible aquatic problems (example issues: alagal blooms, oil, waste, etc.)",
      ]
    return combined_input

def prompt_sensors(measurements):
    combined_input = [
          str(measurements)+ " Use the this water sample data to indentify if this area has a good aquatic health and if present, identify specific aquatic problems (example issues: alagal blooms, oil, waste, etc.)",
      ]
    return combined_input

def generate_prompt(model_name, context, measurements, image):
  if model_name == 'All':
    return prompt_all(context, measurements, image)
  elif model_name == 'Image':
    return prompt_image(image)
  elif model_name == 'Image_Context':
    return prompt_image_context(context, image)
  elif model_name == 'Sensor_Context':
    return prompt_sensor_context(context, measurements)
  elif model_name == 'Sensors':
    return prompt_sensors(measurements)

for m in genai.list_models():
  if 'generateContent' in m.supported_generation_methods:
      print(m.name)

def process_items_in_groups(my_list, model_name, version):
  """
  Processes a list in groups of 4, saving each item to a separate variable.

  Args:
      my_list: The list to be processed.
  """
  for i in range(0, len(my_list), 12):
    # Check if there are enough elements remaining for a full group of 4
    if i + 12 <= len(my_list):
      globals()['Nitrate'] = my_list[i]
      globals()['Nitrite'] = my_list[i + 1]
      globals()['Chlorine'] = my_list[i + 2]
      globals()['Hardness'] = my_list[i + 3]
      globals()['Alkalinity'] = my_list[i + 4]
      globals()['ph'] = my_list[i + 5]
      globals()['Location'] = my_list[i + 6]
      globals()['img_left'] = my_list[i + 7]
      globals()['img_right'] = my_list[i + 8]
      globals()['img_center'] = my_list[i + 9]
      globals()['img_water'] = my_list[i + 10]
      globals()['times'] = my_list[i + 11]

      # ph_mes= 8.3
      # temp_mes= 25.3
      # tds_mes= 805
      # turbidity_mes= 100
      location = Location
      month = times

      img_left_file = img_left
      img_right_file = img_right
      img_center_file = img_center
      img_water_file = img_water


      class SensorMeasurements:
          """
          A class to represent sensor measurements with pH, temperature, TDS, and turbidity.

          Attributes:
              ph (float): The pH value.
              temperature (float): The temperature in degrees Celsius.
              tds (float): The total dissolved solids in mg/L.
              turbidity (float): The turbidity in NTU (Nephelometric Turbidity Units).
          """

          def __init__(self, nitrate, nitrite, chlorine, hardness, alkalinity, ph):
              """
              Initializes a new SensorMeasurements object.

              Args:
                  ph (float): The pH value.
                  temperature (float): The temperature in degrees Celsius.
                  tds (float): The total dissolved solids in mg/L.
                  turbidity (float): The turbidity in NTU.
              """
              self.nitrate = nitrate
              self.nitrite = nitrite
              self.chlorine = chlorine
              self.hardness = hardness
              self.alkalinity = alkalinity
              self.ph = ph

          def __str__(self):
              """
              Returns a string representation of the object.
              """

              return f"Here are the sensor measurements I have collected from the water: (Nitrate={self.nitrate:.2f}mg/L, nitrite={self.nitrite:.2f}mg/L, chlorine={self.chlorine:.2f}mg/L, hardness={self.hardness:.2f} (GH) mg/L), alkalinity={self.alkalinity:.2f} (KH) mg/L), ph={self.ph:.2f}"

      measurements = SensorMeasurements(Nitrate, Nitrite, Chlorine, Hardness, Alkalinity, ph)
      print(measurements)  # Output: SensorMeasurements(pH=7.20, temperature=25.50°C, TDS=350.00 mg/L, turbidity=5.00 NTU)


      class EnvContext:
          def __init__(self, month, location):
              self.month= month
              self.location= location

          def __str__(self):
              return f" I am at the {self.location} in {self.month}."

      context = EnvContext(month, location)
      print(context)

      def to_markdown(text):
        text = text.replace('•', '  *')
        return Markdown(textwrap.indent(text, '> ', predicate=lambda _: True))

      # Or use `os.getenv('GOOGLE_API_KEY')` to fetch an environment variable.

      overlooking_water = PIL.Image.open("/content/drive/MyDrive/gemini_testing/"+ img_left_file)
      surrounding_water = PIL.Image.open("/content/drive/MyDrive/gemini_testing/"+img_right_file)
      display(PIL.Image.open("/content/drive/MyDrive/gemini_testing/"+ img_left_file))

      # Combine URLs in a list
      # image_urls = [overlooking_water, surrounding_water]


      #response = model.generate_content(img)


      # combined_input = [
      #     str(context) + " " + str(measurements)+ " Use the this information and the image provided to indentify if this area has a good aquatic health. If not, identify specific aquatic problems (ex. alagal blooms, oil, watse, etc.) Use factors/objects from both of the two images in the aquatic problem identification. If identified in the images, how can oragnisms impact water quality?",
      #     overlooking_water,
      # ]
      # model_name = 'TBD'
      image_name = overlooking_water
      combined_input = generate_prompt(model_name, context, measurements, image_name)
      model = genai.GenerativeModel(version)

      response = model.generate_content(combined_input)

      response.resolve()
      print(response.text)
      print(site_list[int(i/12)])
      # print(to_markdown(print))
      output_dir = f'/content/drive/MyDrive/gemini_testing/AQS_results/{model_name}'
      if os.path.exists(output_dir) == False:
        os.system(f'mkdir -p {output_dir}')
      output_file_path = f"{output_dir}/{site_list[int(i/12)]}.txt"

      # output_dir = '/content/drive/MyDrive/gemini_testing/AQS_results'
      # output_file_path = f"{output_dir}/{model_name}/{site_list[int(i/12)]}.txt"
      with open(output_file_path, 'w') as file_out:
          file_out.write(response.text + '\n')


# Replace 'your_list' with your actual list
test_list = [35, 0, 0.5, 250, 120, 8.4, 'Columbia Park Pond, Kennewick, WA', 'IMG_2666.jpg', 'IMG_2667.jpg', 'IMG_2666.jpg', 'IMG_2661.jpg', '3:27:00 PM March 2']
process_items_in_groups(data_list, 'Image','gemini-pro-vision')
process_items_in_groups(data_list, 'All', 'gemini-pro-vision')
process_items_in_groups(data_list, 'Image_Context', 'gemini-pro-vision')
process_items_in_groups(data_list, 'Sensor_Context', 'gemini-1.0-pro-latest')
process_items_in_groups(data_list, 'Sensors', 'gemini-1.0-pro-latest')

for i in range(0, len(data_list), 12):
    # Check if there are enough elements remaining for a full group of 4
    if i + 12 <= len(my_list):
      globals()['Nitrate'] = my_list[i]
      globals()['Nitrite'] = my_list[i + 1]
      globals()['Chlorine'] = my_list[i + 2]
      globals()['Hardness'] = my_list[i + 3]
      globals()['Alkalinity'] = my_list[i + 4]
      globals()['ph'] = my_list[i + 5]
      globals()['Location'] = my_list[i + 6]
      globals()['img_left'] = my_list[i + 7]
      globals()['img_right'] = my_list[i + 8]
      globals()['img_center'] = my_list[i + 9]
      globals()['img_water'] = my_list[i + 10]
      globals()['times'] = my_list[i + 11]
    print(int(i/12))